package com.tqfframe;

import com.tqfframe.bean.CustomBean;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.filter.AnnotationTypeFilter;

import java.util.LinkedHashSet;
import java.util.Map;

/**
 * @Author: 唐祺峰
 * @Date: 2022/3/11 0011 13:24
 * @Version 1.0
 */
public class ImportCustomBeanDefinitionRegistrars implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        //获取EnableCustoBean注释的属性
        final Map<String, Object> attributes = importingClassMetadata.getAnnotationAttributes(EnableCustomBeans.class.getName());
        //获取包扫描
        ClassPathScanningCandidateComponentProvider pathScanningCandidateComponentProvider = new ClassPathScanningCandidateComponentProvider(false);
        //添加过滤 带有StarterBeans这个注解的类
        pathScanningCandidateComponentProvider.addIncludeFilter(new AnnotationTypeFilter(StarterBeans.class));

        //定义BeanDefinition列表
        LinkedHashSet<BeanDefinition> candidateComponents = new LinkedHashSet<>();
        for (String basePackages : (String[]) attributes.get("basePackages")) {
            candidateComponents.addAll(pathScanningCandidateComponentProvider.findCandidateComponents(basePackages));
        }
        //注册Bean
        for (BeanDefinition candidateComponent : candidateComponents) {
            registry.registerBeanDefinition(candidateComponent.getBeanClassName(), candidateComponent);
        }
    }
}
